import { Point } from './ts-geometry-2d/Point';
import { AiGTool, DeskBall, HitPath } from './aicore';

// AI击球思考的更像人类
export class AiLevelController {
  public static MaxDistanceSquare = 2000;
  private aiLevel = 0; // L0 L1 L2 L3 L4 L5 L6 L7 L8 L9
  constructor(lv: number) { this.aiLevel = lv; }
  // 球桌距离最大值的平方, 斜对角线的最大值
  public aiLevelController(mainBall: DeskBall, hitPaths: Array<HitPath>, deskBalls: DeskBall[]) {
    if (hitPaths.length > 0) {
      if (hitPaths[0].isDirectHitBall() && hitPaths[0].targetBall) {
        const factors = [1.0, 0.9, 0.8, 0.6, 0.4, 0.2, 0.1, 0, 0, 0, 0];
        const factor = factors[this.aiLevel];
        const allBalls = deskBalls.filter(ba => ba.index !== hitPaths[0].targetBall.index);
        this.changeMicroDirection(mainBall, hitPaths[0], factor, allBalls);
      }
    }
  }

  private changeMicroDirection(mainBall: DeskBall, path: HitPath, factor: number, deskBalls: DeskBall[]) {
    // 击球位置增加一个扰动
    const pos = this.calcuBiasPosition(mainBall.position, path.targetBall.position, path.targetPos, path.targetHole.position, factor);
    if (!AiGTool.hasOccluded(mainBall.position, pos, deskBalls)) {
      path.updateTargetPosition(pos.x, pos.y);
    }
  }

  // 计算偏差击球点的坐标
  private calcuBiasPosition(mainPos: Point, ballPos: Point, targetPos: Point, holePos: Point, levelFactor: number) {
    const dists = (targetPos.x - holePos.x) * (targetPos.x - holePos.x) + (targetPos.y - holePos.y) * (targetPos.y - holePos.y);
    const totalFactor = levelFactor *  dists / AiLevelController.MaxDistanceSquare;
    const dirx = targetPos.x + totalFactor * (Math.random() - 0.5);
    const diry = targetPos.y + totalFactor * (Math.random() - 0.5);
    return new Point(dirx, diry);
  }
}

